package com.three.reward.impl;

import com.three.config.LanguageConfig;
import com.three.constant.LanguageId;
import com.three.domain.player.PlayerAttrType;
import com.three.domain.player.PlayerPo;
import com.three.exception.GameException;
import com.three.repository.PlayerRepository;
import com.three.reward.RewardBase;
import com.three.reward.RewardItem;
import com.three.utils.SpringUtils;

/**
 * 玩家属性奖励
 * Created by Mathua on 2017/6/23.
 */
public final class PlayerAttrReward extends RewardBase {
    public PlayerAttrReward(RewardItem item, long holderId) {
        super(item, holderId);
    }

    @Override
    public void canHandOut() throws GameException {
        PlayerPo player =  SpringUtils.getBean(PlayerRepository.class).getOne(holderId);
        PlayerAttrType playerAttr = PlayerAttrType.valueOf((int) param);
        if(playerAttr.getAttrValue(player) + amount > playerAttr.getLimit(player)) {
            String errorMsg = LanguageConfig.getText(LanguageId.HAND_OUT_FAIL_BY_OVER_FLOW);
            String param = LanguageConfig.getText(playerAttr.getNameId());
            throw new GameException(LanguageConfig.replacePattern(errorMsg, param));
        }
    }

    @Override
    public RewardItem handOutReward(boolean overflowToMail) {
        PlayerPo player = SpringUtils.getBean(PlayerRepository.class).getOne(holderId);
        PlayerAttrType playerAttr = PlayerAttrType.valueOf((int) param);
        long oldValue = player.getAttrValue(playerAttr);
        player.addAttrValue(playerAttr, amount);
        // 溢出的时候发邮件
        if(overflowToMail) {
            long nowValue = player.getAttrValue(playerAttr);
            long leftValue = amount - (nowValue - oldValue);
            // 有剩余的时候返回剩余的物品信息
            if(leftValue > 0) {
                return RewardItem.build(type, param, leftValue);
            }
        }
        return null;
    }
}
